package stopthread;

import org.junit.jupiter.api.Test;

/**
 * 判断当前线程是否是停止状态
 * this.interrupted() 测试当前线程是否已中断
 * this.isInterrupted() 测试线程是否已中断
 */
public class Demo_02 {

    /**
     * false
     * false
     */
    @Test
    public void testInterrupted_1() {
        try{
            MyThread thread = new MyThread();
            thread.start();
            Thread.sleep(1000);
            //设置为"中断"状态
            thread.interrupt();
            System.out.println(" 是否停止1？=" + thread.interrupted());
            System.out.println(" 是否停止2？=" + thread.interrupted());
        }catch (InterruptedException e){
            System.out.println("main catch");
            e.printStackTrace();
        }
    }

    /**
     * true
     * false
     * interrupted 会清除线程的中断状态为false
     */
    @Test
    public void testInterrupted_2() {
        //设置为"中断"状态
        Thread.currentThread().interrupt();
        System.out.println(" 是否停止1？=" + Thread.interrupted());
        System.out.println(" 是否停止2？=" + Thread.interrupted());
    }

    /**
     * true
     * true
     */
     @Test
    public void testInterrupted_3() {
        //设置为"中断"状态
        Thread.currentThread().interrupt();
        System.out.println(" 是否停止1？=" + Thread.interrupted());
        Thread.currentThread().interrupt();
        System.out.println(" 是否停止2？=" + Thread.interrupted());
    }

    /**
     * true
     * true
     * interrupt 不会清除线程状态标志
     */
    @Test
    public void testIsInterrupted() {
        try {
            MyThread thread = new MyThread();
            thread.start();
            Thread.sleep(100);
            thread.interrupt();
            System.out.println(" 是否停止1？=" + thread.isInterrupted());
            System.out.println(" 是否停止2？=" + thread.isInterrupted());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("end!");
    }

}

